<template>
  <base-breadcrumb>
    <searchData :search-data="searchArr" @search="search" />

    <a-card>
      <!-- :row-selection="{ selectedRowKeys: selectedRowKeys, onChange: onSelectChange }" -->
      <list-table
        :loading="loading.isTable"
        :request="loadData"
        ref="table"
        :columns="columns"
        :startIndex="0"
        :outSelectedRowKeys.sync="selectedKeys"
        :export-config="{ use: true, select: '施组方案管理台账', all: '施组方案管理台账' }"
        :is-show-count-bar="false"
        @select-click="selectClick"
        :export-permission="{ select: 'tm_052_exp_01', all: 'tm_052_exp_02' }"
      >
        <a-button
                slot="prefix"
                class="mb12"
                icon="download"
                type="primary"
                :disabled="!selectedKeys.length"
                @click="batchExportFiles"
                v-btn-permission="'tm_052_bat_03'"
        >批量下载附件</a-button>
        <a-collapse v-model="activeKey" :bordered="false" expand-icon-position="right" slot="suffix" class="mb12">
          <a-collapse-panel style="background: #e6f3fc; border: none" :show-arrow="false">
            <template slot="header">
              <a-row type="flex" justify="space-between" align="middle" style="width: 100%">
                <div>
                  <a-icon style="color: #108ee9" type="exclamation-circle" />
                  <span>
                    已选择<a>{{ selectLength || 0 }}</a> 项</span
                  >
                  <span>
                    总计：<a>{{ totalInfo.total || 0 }}</a></span
                  >
                  <span>
                    A：<a>{{ totalInfo.approveA  || 0 }}</a> 个</span
                  >
                  <span
                    >{{ ' | ' }}B：<a>{{ totalInfo.approveB  || 0 }}</a> 个</span
                  >
                  <span
                    >{{ ' | ' }}C：<a>{{ totalInfo.approveC  || 0 }}</a> 个</span
                  >
                  <span
                    >{{ ' | ' }}D：<a>{{ totalInfo.approveD || 0 }}</a> 个</span
                  >
                  <span
                    >{{ ' | ' }}施组：<a>{{ totalInfo.approveConstruction || 0 }}</a> 个</span
                  >
                </div>
                <div>
                  <a class="btn_right">
                    <span>{{ activeKey.length > 0 ? '收起' : '展开' }}详细汇总信息</span>
                    <a-icon :type="activeKey.length > 0 ? 'up' : 'down'" />
                  </a>
                </div>
              </a-row>
            </template>
            <div class="combox-table-wrapper" v-if="totalInfo.countDetail&&totalInfo.countDetail.length">
              <div class="table-div">
                <ul class="table-ul">
                  <li class="table-li">
                    <div>统计类型</div>
                    <div>统计信息</div>
                  </li>
                  <li>
                    <div>问题</div>
                    <div>
                      <span>问题总数:<a>{{totalInfo.countDetail[0].afield}}</a></span
                      ><b>|</b><span>问题已回复总数:<a>{{totalInfo.countDetail[0].bfield}}</a></span>
                    </div>
                  </li>
                  <li>
                    <div>方案交底</div>
                    <div>
                      <span>已交底方案数:<a>{{totalInfo.countDetail[1].afield}}</a></span
                      ><b>|</b><span>未完成交底方案数:<a>{{totalInfo.countDetail[1].bfield}}</a></span>
                    </div>
                  </li>
                  <li>
                    <div>技术交底</div>
                    <div>
                      <span>已交底方案数:<a>{{totalInfo.countDetail[2].afield}}</a></span
                      ><b>|</b><span>未交底方案数:<a>{{totalInfo.countDetail[2].bfield}}</a></span>
                    </div>
                  </li>
                  <li>
                    <div>复核</div>
                    <div>
                      <span>复核方案数量:<a>{{totalInfo.countDetail[3].afield}}</a></span
                      ><b>|</b><span>复核方案次数:<a>{{totalInfo.countDetail[3].bfield}}</a></span>
                    </div>
                  </li>
                  <li>
                    <div>实施</div>
                    <div>
                      <span>未实施:<a>{{totalInfo.countDetail[4].afield}}</a></span
                      ><b>|</b><span>实施中:<a>{{totalInfo.countDetail[4].bfield}}</a></span
                      ><span>实施完成:<a>{{totalInfo.countDetail[4].cfield}}</a></span
                      ><b>|</b><span> 实施完成率:<a>{{totalInfo.countDetail[4].fieldRate?totalInfo.countDetail[4].fieldRate*100 + '%': 0}}</a></span>
                    </div>
                  </li>
<!--                  <li>-->
<!--                    <div style="line-height: 90px">验收</div>-->
<!--                    <div>-->
<!--                      <p style="border-bottom: 1px solid #e8e8e8">-->
<!--                        <span>危大方案验收数（A+B）:<a>100</a></span-->
<!--                        ><b>|</b><span>危大方案验收次数（A+B）:<a>100</a></span-->
<!--                        ><b>|</b><span>危大方案验收率（A+B）:<a>100</a></span>-->
<!--                      </p>-->
<!--                      <p style="border-bottom: 1px solid #e8e8e8">-->
<!--                        <span>超危大方案验收数（A）:<a>100</a></span-->
<!--                        ><b>|</b><span>超危大方案验收次数（A）:<a>100</a></span-->
<!--                        ><b>|</b><span> 超危大方案验收率（A）:<a>100</a></span>-->
<!--                      </p>-->
<!--                      <p>-->
<!--                        <span>危大方案验收数（B）:<a>100</a></span-->
<!--                        ><b>|</b><span>危大方案验收次数（B）:<a>100</a></span-->
<!--                        ><b>|</b><span>超危大方案验收率（B）:<a>100</a></span>-->
<!--                      </p>-->
<!--                    </div>-->
<!--                  </li>-->
                </ul>
              </div>
            </div>
          </a-collapse-panel>
        </a-collapse>
        <span slot="description" slot-scope="text">
          <ellipsis :length="8" tooltip>{{ text }}</ellipsis>
        </span>
        <span slot="version" slot-scope="text, record" style="cursor: pointer; color: #108de9" @click="versionList(record)"> {{ text?'V'+text: '' }} </span>
        <!-- 操作 -->
        <span slot="operation" slot-scope="text, record">
          <MoreButton>
            <a  @click="detailed(record)" v-btn-permission="'tm_052_loo_02'">查看</a>
            <a  @click="supplementFn(record)" v-if="record.show" v-btn-permission="'tm_052_sup_04'">补充</a>
          </MoreButton>
        </span>

        <template slot="status" slot-scope="text, record">
          <list-status :color="listStatusMap[record.status]" :isApproval="true" conversion="en" :text="text"></list-status>
        </template>
      </list-table>
      <div></div>
    </a-card>
    <Version :visible="visible.versionVisible" @cancel="visible.versionVisible = false" :versionId="versionId" :row="row"></Version>
    <Supplement :visible="visible.supplementVisible"
                v-if="visible.supplementVisible"
                @cancel="visible.supplementVisible = false"
                @handleSuccess="handleSuccess"
                :row="row"
    ></Supplement>
  </base-breadcrumb>
</template>
  
  <script>
import { Collapse } from 'ant-design-vue' // ant
import OrgTreeSelect from '@/components/OrgTreeSelect'
import { getList, getListTotal, deleteList, getGroupCount, getTotalCount } from '@/api/technical/approval'
import { technicalQueryPage, technicalApprovalCount, downListzip } from '@/api/technology'
import { listOption } from '@/api/technical/approvalPlan'
import SelectProjectType from '@/components/Select/SelectProjectType' // 工程类别
import Version from './version.vue' //历史版本号
import Supplement from './supplement.vue' //补充
const columns = [
  { title: '施组（方案名称）', dataIndex: 'schemeName', ellipsis: true },
  {title: '方案类型',dataIndex: 'schemeCategory',ellipsis: true},
  {title: '所属分公司',dataIndex: 'branchCompany'},
  {title: '所属项目',dataIndex: 'projectName'},
  {title: '版本号',dataIndex: 'versionNumber',scopedSlots: { customRender: 'version' }},
  {title: '意见回复状态',dataIndex: 'replyStatus'},
  {title: '意见回复时间',dataIndex: 'replyTime'},
  {title: '方案交底状态',dataIndex: 'confessAuditStatusName'},
  {title: '方案交底时间',dataIndex: 'confessAuditStatusTime'},
  {title: '技术交底状态',dataIndex: 'technologyStatusName'},
  {title: '技术交底时间',dataIndex: 'technologyStatusTime',ellipsis: true},
  {title: '复核状态',dataIndex: 'reAuditStatus',ellipsis: true},
  {title: '复核时间',dataIndex: 'reAuditTime',ellipsis: true},
  // {title: '验收状态',dataIndex: 'reportingPeople4',ellipsis: true},
  // {title: '验收时间',dataIndex: 'reportingPeople5',ellipsis: true},
  {title: '实施状态',dataIndex: 'implStatusStr',ellipsis: true},
  {title: '报审状态',dataIndex: 'auditStatus',ellipsis: true},
  {title: '操作',dataIndex: 'operation',width: '230px',scopedSlots: { customRender: 'operation' }}
]
export default {
  name: 'a' + Date.now(),
  components: {
    ACollapse: Collapse,
    ACollapsePanel: Collapse['Panel'],
    Version,
    Supplement
  },
  filters: {
    filterRate(rate) {
      if (Number.isFinite(rate)) {
        return (rate * 100).toFixed(2) + '%'
      }
      return '0%'
    }
  },
  data() {
    this.columns = columns
    return {
      versionId: '',
      schemeTypeData: [],
      totalInfo: {
        countDetail: []
      }, // 统计信息
      activeKey: [],
      childInitData: {},
      selectLength: 0,
      visible: {
        approvalDetails: false,
        versionVisible: false,
        excellenceVisible: false,
        supplementVisible: false
      },
      loading: {
        isTable: false,
        exportChecked: false,
        exportAll: false
      },
      qualityTypes: [],
      dataSource: [],
      advanced: false,
      totalSize: 0,
      option: [],
      total: {},
      reportingTime: [],
      completeDate: [],
      objFrom: {
        pageNo: 1,
        pageSize: 10,

        whetherProfessionalSubcontracting: '',
        whetherMajorExpense: ''
      },
      selectedRowKeys: [],
      selectedRows: [],
      listStatusMap: {
        DRAFT: 'yellow',
        SUBMITTED: 'blue',
        PAST: 'green',
        REJECTED: 'red',
        DRAFT_CHANGE: 'yellow',
        SUBMITTED_CHANGE: 'blue',
        PAST_CHANGE: 'green',
        REJECTED_CHANGE: 'red'
      },
      pathName: this.$route.path,
      queryParam: {},
      totalNum: 0,
      selectedKeys: [],
      typeOption: [],
      row:{},
      loadData: (parameter) => {
        if (this.loading.isTable) return
        this.loading.isTable = true
        const { whetherProfessionalSubcontracting, whetherMajorExpense, projectName } = this.objFrom
        const params = {
          // ...this.objFrom,
          ...this.queryParam,
          ...parameter,
          projectName: projectName || void 0,
          whetherProfessionalSubcontracting: whetherProfessionalSubcontracting !== '' && whetherProfessionalSubcontracting !== void 0 ? !!whetherProfessionalSubcontracting : void 0,
          whetherMajorExpense: whetherMajorExpense !== '' && whetherMajorExpense !== void 0 ? !!whetherMajorExpense : void 0
        }
        // this.loadComboxTable(params) // 调用统计分组
        if (this.$refs.comBoxTable) {
          this.$refs.comBoxTable.refresh()
        }
        this.getTotalCountReq(params) // 调用统计信息 technicalQueryPage
        return technicalQueryPage(params)
          .then((res) => {
            res.data.forEach(item=>{
              if(item.auditStatus === 'PAST' || item.auditStatus === 'PAST_CHANGE' ) {
                item.auditStatus = ''
              }

              if(!item.auditStatus || item.auditStatus.indexOf('不通过')>-1 || item.auditStatus.indexOf('一审')>-1) {
                item.show = true
              } else {
                item.show = false
              }
            })
            this.loading.isTable = false
            this.totalNum = res.totalSize
            return res
          })
          .catch(() => {
            this.loading.isTable = false
          })
      }
    }
  },
  created() {
    this.reportingTime = ['2021-01-01', this.$dateFormat(new Date(), 'D')]
    this.changeReportingTime('', this.reportingTime)
    // this.getList()
    // this.getListTotal()
    this.focusOption()
  },
  computed: {
    searchArr() {
      return [
        { name: '所属单位', valueKey: 'searchQuery', type: OrgTreeSelect },
        { name: '方案名称', value: 'schemeName', type: 'input' },
        { name: '方案类型', value: 'schemeCategory', type: 'select', data: this.typeOption },
        { name: '审批完成时间', value: 'completeDate', type: 'dateRange', attr: { rangeFormat: ['endAuditDateStart', 'endAuditDateEnd'] } },
        { name: '工程类别', type: SelectProjectType, valueKey: 'projectQualityTypeId', showStop: false },
        { name: '危大工程范围', value: 'dangerName', type: 'input' }
      ]
    }
  },
  mounted() {
    this.listOption()
    this.$bus.$on('handleRefresh' + this.pathName, () => {
      this.getList()
    })
  },
  beforeDestroy() {
    console.log('beforeDestroy-------table的Path', this.pathName)
    this.$bus.$off('handleRefresh' + this.pathName)
  },
  methods: {
    handleSuccess() {
      this.visible.supplementVisible = false
      this.$refs.table.refresh(true)
    },
    listOption() {
      listOption({ type: '5' }).then((res) => {
        this.typeOption = res.data;
        if(this.typeOption.length){
          this.typeOption.map((item)=>{
            item.label = item.name;
            item.value = item.id;
          })
        }
      })
    },
    batchExportFiles() {
      const data = {
        ids:this.selectedKeys,
        typeId: 0,
        urlStr: window.location.origin
      }
      downListzip(data).then(res=>{
        this.handleDownload(res)
      })
    },
    /**
     * 转义下载
     * @param parameter
     */
    handleDownload(res) {
      const blob = new Blob([res.data])
      const filename = decodeURIComponent(res.headers['content-disposition'].split('filename=')[1])
      console.log('filenamefilename',filename)
      const downloadElement = document.createElement('a')
      const href = window.URL.createObjectURL(blob) // 创建下载的链接
      downloadElement.href = href
      downloadElement.download = filename.substring(filename.indexOf("''") + 1) // 获取文件名
      document.body.appendChild(downloadElement)
      downloadElement.click() //点击下载
      document.body.removeChild(downloadElement) //下载完成移除元素
      window.URL.revokeObjectURL(href) //释放blob对象
    },
    //补充
    supplementFn(row) {
      this.row = row
      this.visible.supplementVisible = true
    },
    selectClick(a, b) {
      this.selectLength = a.rows.length
    },
    //点击查看版本号
    versionList(data) {
      this.row = data
      this.versionId = data.id
      this.visible.versionVisible = true

    },
    handleExportChecked() {
      const list = this.selectedRows
      const columns = this.columns
      this.$refs.exportBtnOne.generateExcel(list, { columns: columns }, 0)
    },
    async getTotalCountReq(params) {
      try {
        const res = await technicalApprovalCount(params)
        this.totalInfo = res.data
      } catch (e) {
        console.error(e)
      }
    },
    toggleApprovalDetails(data) {
      this.childInitData = { ...data }
      this.visible.approvalDetails = true
    },
    // 统计
    focusOption() {
      this.listOption()
    },
    changeReportingTime(value, dateString) {
      this.objFrom.reportingTimeStart = dateString[0]
      this.objFrom.reportingTimeEnd = dateString[1]
    },
    // 获取列表数据
    search(val = {}) {
      this.queryParam = {
        ...val
      }
      this.$refs.table.refresh(true)
    },
    getList() {
      this.$refs.table.refresh(true)
    },
    //新增
    handleAdd() {
      this.$router.push({
        path: '/technical/ShiGroup/Approval/EditFrom',
        query: {
          type: 'add'
        }
      })
    },
    //编辑
    addEdit(record, type) {
      this.$router.push({
        path: '/technical/ShiGroup/Approval/EditFrom',
        query: {
          type,
          id: record.id
        }
      })
    },
    //查看
    detailed(record) {
      this.$router.push({
        path: '/technical/ShiGroup/administrativeLedger/detail',
        query: {
          type: 'view',
          id: record.id,
          confessAuditStatusId: record.confessAuditStatusId,
          reAuditId: record.reAuditId ? record.id : '',
          replyId: record.replyId ? record.id : '',
          technologyStatusId: record.technologyStatusId ? record.id: '',
          conId: record.id,
          versionNumber: record.versionNumber
        }
      })
    },
    //变更
    changeDetail(record) {
      let isSchemeCategoryA = record.schemeCategory === 'A' //是否是A方案
      this.$router.push({
        path: '/technical/ShiGroup/Approval/EditFrom',
        query: {
          type: 'changeDetail',
          id: record.id,
          isSchemeCategoryA
        }
      })
    },
    //推优
    promoteExcellenceFn(data) {
      this.visible.excellenceVisible = true
    }
  }
}
</script>
<style scoped lang="less">
.combox-table-wrapper {
  .table-div {
    width: 100%;
    background-color: #ffffff;
    ul {
      margin: 0;
      padding: 0;
    }
    li {
      display: flex;
      > div {
        padding: 10px 10px;
        border: 1px solid #e8e8e8;
        border-bottom: none;
      }
      & > div:first-child {
        width: 200px;
        border-right: none;
      }
      & > div:last-child {
        flex: 1;
        & > span {
          margin-right: 10px;
        }
        b {
          margin-right: 10px;
          font-weight: normal;
        }
      }
      &:last-child {
        > div {
          padding: 10px 10px;
          border-bottom: 1px solid #e8e8e8;
          p {
            margin-bottom: 0;
            line-height: 30px;
            b {
              margin: 0 10px;
            }
          }
        }
      }
      &:first-child {
        font-weight: bold;
        div {
          background-color: #f4f4f4;
        }
      }
    }
  }
}
</style>
  